package com.onerm.store;

import java.util.Collections;
import java.util.List;

import org.joda.time.DateTimeZone;
import org.joda.time.format.DateTimeFormatter;
import org.joda.time.format.ISODateTimeFormat;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;

public class SqlLiteDataInterface implements DataInterface {

  private final SQLiteDatabase database;

  private static final DateTimeFormatter DATE_FORMAT
      = ISODateTimeFormat.dateTime().withZone(DateTimeZone.UTC);

  public SqlLiteDataInterface(SQLiteDatabase database) {
    this.database = database;
  }

  @Override
  public Iterable<String> getExerciseNames() {
    Cursor cursor = database.query(
            "exercise",
            new String[] {"exercise_name"}, null, null, null, null, null);
    if (cursor != null && cursor.moveToFirst()) {
      List<String> list = Lists.newArrayList();
      while (!cursor.isAfterLast()) {
        String next = cursor.getString(0);
        list.add(next);
        cursor.moveToNext();
      }
      cursor.close();
      return list;
    } else {
      return Collections.emptyList();
    }
  }

  @Override
  public void logExercise(int exerciseId, int numReps, double weight) {
    Preconditions.checkArgument(numReps > 0);
    Preconditions.checkArgument(weight >= 0);
    String sqlCmd = String.format(
        "INSERT INTO setlog(" +
          "setlog_exercise_id, setlog_num_reps, setlog_weight, setlog_date) " +
        "values ('%d', '%d', '%.2f', '%s')",
        exerciseId, numReps, weight,
        DATE_FORMAT.print(System.currentTimeMillis()));
    database.execSQL(sqlCmd);
  }
}
